import React, { useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { Outlet, useLocation, useNavigate } from 'react-router-dom';
import { AppStore } from '../../types';
import main, { AppLocalKey } from '../../main';
import { userRequest } from '../../redux/userReducer';

export default function MainPage() {
  const location = useLocation();
  const dispatch = useDispatch();
  const user = useSelector((s: AppStore) => s.user);
  const [over, setOver] = useState(false);
  const navigate = useNavigate();

  useEffect(() => {
    if (!over) checkLoginKey();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  useEffect(() => {
    if (!over) {
      checkLoginState();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [user]);

  function checkLoginKey() {
    let key = localStorage.getItem(AppLocalKey.loginToken);
    main.loginKey = key;
    let tmp = location.pathname + location.search;
    if (!key) {
      setOver(true);
      if (tmp.startsWith('/register') || tmp.startsWith('register')) {
        navigate(tmp);
      } else {
        navigate('/login');
      }
    } else {
      dispatch(userRequest({ token: key }));
    }
  }

  function checkLoginState() {
    if (user.loaded) {
      setOver(true);
      let tmp = location.pathname + location.search;
      if (user.user?.userId) {
        if (tmp.length <= 0 || tmp === '/' || tmp.startsWith('/login' || tmp.startsWith('login'))) {
          tmp = '/home';
          navigate(tmp);
        }
      } else {
        if (tmp.startsWith('/register') || tmp.startsWith('register')) {
          navigate(tmp);
        } else {
          navigate('/login');
        }
      }
    }
  }

  return <Outlet />;
}
